package com.example.yiqinmanagersystem.controller.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.yiqinmanagersystem.entity.ChinaToal;
import com.example.yiqinmanagersystem.entity.NocvData;
import com.example.yiqinmanagersystem.service.ChinaTotalService;
import com.example.yiqinmanagersystem.service.DataDisplayService;
import com.example.yiqinmanagersystem.vo.NocvDataVo;
import com.example.yiqinmanagersystem.vo.ResponseCode;
import com.example.yiqinmanagersystem.vo.ResponseResult;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/*
 **@Author:youpeng
 **Created on 2022/9/12
 */
@RestController
@RequestMapping("/api")
public class MapDataManagerController {

    @Resource
    private DataDisplayService dataDisplayService;

    @Resource
    private ChinaTotalService chinaTotalService;

    /*
    * 实现获取实时数据并渲染（确诊，疑似，死亡，输入）
    * */
    @GetMapping("/china/getChinaTotalData")
    public ResponseResult getChinaTotalData(Model model){
        ChinaToal chinaToal = chinaTotalService.getById(1);
        model.addAttribute("chinaTotal",chinaToal);
        if(chinaToal!=null){
            return new ResponseResult(ResponseCode.SUCCESS,1,chinaToal);
        }else {
            return new ResponseResult(ResponseCode.FAILED);
        }
    }

    /*
    * 获取疫情地图数据
    * */
    @GetMapping("/china/listDataByPage")
    public ResponseResult listDataByPage(NocvDataVo nocvDataVo){
        //1.创建分页对象，并限制大小
        IPage<NocvData> page = new Page<>(nocvDataVo.getPage(), nocvDataVo.getLimit());
        //2.创建模糊查询条件
        QueryWrapper<NocvData> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(!(nocvDataVo.getName()==null),"name",nocvDataVo.getName());
        //3.疫情数据确诊最多的排在最前面
        queryWrapper.orderByDesc("value");
        //4.查询数据库
        IPage<NocvData> dataIPage = dataDisplayService.page(page, queryWrapper);
        //5.返回json数据格式封装
        if(dataIPage.getSize()!=0){
            return new ResponseResult(ResponseCode.SUCCESS, Math.toIntExact(page.getTotal()),page.getRecords());
        }else {
            return new ResponseResult(ResponseCode.FAILED);
        }
    }

    /*
    * @Description 删除疫情数据逻辑
    * @Params Integer id
    * @Return
    * */
    @PostMapping("/china/deleteById")
    public ResponseResult deleteById(Integer id){
        boolean b = dataDisplayService.removeById(id);
        if(b){
            return new ResponseResult(ResponseCode.SUCCESS);
        }else {
            return new ResponseResult(ResponseCode.FAILED);
        }
    }

    /*
    * @Description 新增或修改 【id】
    *   id ：nocvData 有值修改 无值新增
    * @Params nocvData
    * @return
    * */
    @PostMapping("/china/addOrUpdateChina")
    public ResponseResult addOrUpdateChina(NocvData nocvData){
        boolean b = dataDisplayService.saveOrUpdate(nocvData);
        if(b){
            return new ResponseResult(ResponseCode.SUCCESS);
        }else {
            return new ResponseResult(ResponseCode.FAILED);
        }
    }

    /*
     * @Description 文件拖拽上传
     * @return
     * */
    @PostMapping("/china/excelImportChina")
    public ResponseResult excelImportChina(@RequestParam("file") MultipartFile file) throws Exception{
        //1.文件不能为空
        if(file.isEmpty()){
            ResponseCode.FAILED.setMsg("文件不能为空");
            new ResponseResult(ResponseCode.FAILED);
        }
        //2.poi 获取 excel 解析数据
        XSSFWorkbook wb = new XSSFWorkbook(file.getInputStream());
        XSSFSheet sheet = wb.getSheetAt(0);
        //3.接受解析数据
        ArrayList<NocvData> list = new ArrayList<>();
        XSSFRow row = null;
        for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {
            NocvData nocvData = new NocvData();
            row = sheet.getRow(i);
            nocvData.setName(row.getCell(0).getStringCellValue());
            nocvData.setValue((int) row.getCell(1).getNumericCellValue());
            list.add(nocvData);
        }
        //4.插入数据库
        boolean b = dataDisplayService.saveBatch(list);
        if(b){
            return new ResponseResult(ResponseCode.SUCCESS);
        }else {
            return new ResponseResult(ResponseCode.FAILED);
        }
    }

    /*
    * @Description excel 文件导出
    * */
    @GetMapping("/china/excelOutPortChina")
    public void excelOutPortChina(HttpServletResponse response ){
        //1.查询数据库数据
        List<NocvData> list = dataDisplayService.list();
        //2.建立Excel对象，封装数据
        response.setCharacterEncoding("UTF-8");
        XSSFWorkbook xb = new XSSFWorkbook();
        XSSFSheet sheet = xb.createSheet("中国疫情数据sheet");
        XSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("城市名称");
        row.createCell(1).setCellValue("确诊人数");
        //3.封装数据
        for (NocvData nocvData : list) {
            XSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
            dataRow.createCell(0).setCellValue(nocvData.getName());
            dataRow.createCell(1).setCellValue(nocvData.getValue());
        }
        //4.输出流文件
        OutputStream outputStream = null;
        response.setContentType("application/octet-stream;charset=utf-8");
        try {
            response.setHeader("Content-Disposition","attachment;filename="+new String("中国疫情地图数据表".getBytes(),"iso-8859-1")+".xls");
            outputStream = response.getOutputStream();
            xb.write(outputStream);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //5.关闭流
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ;
    }
}
